package collector.httpd;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.apexcns.core.util.XmlBindUtil;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Request;
import org.springframework.web.bind.ServletRequestDataBinder;

import collector.core.xml.Result;

public class HttpdUtil {

	public static void addHeaderNoCache(HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache, must-revalidate");	// HTTP/1.1
		response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");		// Date in the past
	}

	public static void handleUnknown(String target, Request request
			, HttpServletRequest httpRequest, HttpServletResponse response)
	throws IOException, ServletException {
		request.setHandled(true);
		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		StringBuilder strb = new StringBuilder();
		strb.append("No Handler for <b>" + target + "</b>");
		response.getWriter().println(strb.toString());
	}

	public static boolean checkAuth(Request request, HttpServletResponse response
			, String username, String password) throws UnsupportedEncodingException {
		boolean needAuth = StringUtils.isNotEmpty(username);
		boolean isAuth = false;
		
		if(!needAuth) return true;

		byte[] authBase64 = Base64.encodeBase64((username + ":" + password).getBytes());
		String authString = new String(authBase64, "UTF-8");
		String realmName = "Auth";
		try {
			String auth = request.getHeader("Authorization");
			String enc = auth.split(" ", 2)[1];
			isAuth = authString.equals(enc);
		} catch (Exception e) {
		}
		if(!isAuth) {
			try {
				request.setHandled(true);
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				response.addHeader("WWW-Authenticate", "Basic realm=\"" + realmName + "\"");
				response.getWriter().println("<h1>Authentication required!</h1>");
			} catch (IOException e1) {
			}
		}
		return isAuth;
	}
	
	
	public static Object bindRequestBean(Object bean, ServletRequest request) {
		ServletRequestDataBinder binder = new ServletRequestDataBinder(bean);
		binder.bind(request);
//		if (bean instanceof Factory) {
//			bean = ((Factory) bean).getBean();
//		}
		return bean;
	}

	
	public static void handleXmlOutput(Result result, HttpServletResponse response) throws IOException {
		String ret = XmlBindUtil.toXml(Result.class, result);
		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("text/xml");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(ret);
	}

}
